package com.tj.jinzao.presenter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.Base64Coder;
import com.tj.jinzao.base.BasePresenter;
import com.tj.jinzao.base.IBaseView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.common.Settings;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.DetectQuestion;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 识别处理
 * Created by wjy 2018/12/10.
 */
public class DetectPresenter extends BasePresenter<IBaseView<List<DetectQuestion>>> {

    private final static String CHAR_TAG[] = new String[]{
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
    };

    public DetectPresenter(IBaseView<List<DetectQuestion>> view) {
        super(view);
    }

    public void getQuestionList() {
        addSubscription(mApiService.getQuestionList(), new SubscriberCallBack<List<DetectQuestion>>(mView.getContext()) {
            @Override
            protected void onSuccess(List<DetectQuestion> list) {
                if (mView != null) mView.onRequestSuccess(list);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    /**
     * 上传文件
     */
    public void checkTongue(final String localPath) {
        //构建body
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //文件参数
        if (!TextUtils.isEmpty(localPath)) {
            File file = new File(localPath);
            if (file.isFile()) {
                builder.addFormDataPart("img", file.getName(), RequestBody.create(MediaType.parse("*/*"), file));
            }
        } else {
            return;
        }
        RequestBody build = builder.build();
        addSubscription(mApiService.checkTongue(build), new SubscriberCallBack<String>(mView.getContext()) {
            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onSuccess(String response) {
                if(TextUtils.equals("true",response)){
                    uploadTonguePic(localPath);
                }else {
                    if (mView != null) {
                        mView.onRequestError(null);
                    }
                }
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) {
                    mView.onRequestError(null);
                }
            }
        });
    }

    /**
     * 上传舌头文件
     */
    public void uploadTonguePic(String filePath) {
        File file = new File(filePath);
        OkHttpClient client = new OkHttpClient();
        try {
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("photo", file.getName(), fileBody)
                    .build();
            Request request = new Request.Builder()
                    .url(Constant.BASE_SERVER_URL + "api/photos/tongue")
                    .post(requestBody)
                    .addHeader("Authorization", String.valueOf(UserManager.getInstance().getUser().getAuthentication()))
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (mView != null) {
                        mView.onRequestError(null);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject data = new JSONObject(response.body().string());
                        boolean isSuccess = data.optBoolean("detectRes");
                        if (Constant.SHOW_DETECT_BITMAP) {
                            ToastUtils.showToast(mView.getContext(), "上传成功，舌头图片是否合格：" + isSuccess);
                        }
                        if (isSuccess) {
                            long id = data.optLong("id");
                            Settings.setLong(mView.getContext(), Settings.KEY_PREF_TONGUE_ID, id);
                            if (mView != null) {
                                mView.onRequestSuccess(null);
                            }
                        } else {
                            if (mView != null) {
                                mView.onRequestError(null);
                            }
                        }

                    } catch (Exception e) {
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String base64Image;
    /**
     * 传入url 先压缩 后转为base64
     * @param srcPath
     * @return
     */
    private String getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 1280f;//这里设置高度为800f
        float ww = 720f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImageToBase64(bitmap);//压缩好比例大小后再进行质量压缩
    }


    private String compressImageToBase64(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        byte[] bytes = baos.toByteArray();
        Log.e("preencode", new String(bytes));
        String url = new String(Base64Coder.encode(bytes));
        return  url;


    }

    /**
     * 上传脸部文件
     */
    public void uploadFacePic(String filePath) {
        File file = new File(filePath);
        OkHttpClient client = new OkHttpClient();
        try {
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("photo", file.getName(), fileBody)
                    .build();
            Request request = new Request.Builder()
                    .url(Constant.BASE_SERVER_URL + "api/photos/face")
                    .post(requestBody)
                    .addHeader("Authorization", String.valueOf(UserManager.getInstance().getUser().getAuthentication()))
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (mView != null) {
                        mView.onRequestError(null);
                        if (Constant.SHOW_DETECT_BITMAP) {
                            ToastUtils.showToast(mView.getContext(), "上传失败");
                        }
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject data = new JSONObject(response.body().string());
                        boolean isSuccess = data.optBoolean("detectRes");
                        if (Constant.SHOW_DETECT_BITMAP) {
                            ToastUtils.showToast(mView.getContext(), "上传成功，图片是否合格：" + isSuccess);
                        }
                        if (isSuccess) {
                            long id = data.optLong("id");
                            Log.i("wjy", "face id：" + id);


                            Settings.setLong(mView.getContext(), Settings.KEY_PREF_FACE_ID, id);
                            if (mView != null) {
                                mView.onRequestSuccess(null);
                            }
                        } else {
                            if (mView != null) {
                                mView.onRequestError(null);
                            }
                        }

                    } catch (Exception e) {
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    public void dealChoose(List<DetectQuestion> questions) {
        try {
            JSONObject object = new JSONObject();
            long faceId = Settings.getLong(mView.getContext(), Settings.KEY_PREF_FACE_ID, 0);
            object.put("face_result_id", faceId);
            long tongueId = Settings.getLong(mView.getContext(), Settings.KEY_PREF_TONGUE_ID, 0);
            object.put("tongue_result_id", tongueId);
            JSONArray array = new JSONArray();
            for (DetectQuestion question : questions) {
                JSONObject o = new JSONObject();
                o.put("id", String.valueOf(question.getId()));
                boolean answers[] = question.getSelect();
                JSONArray answer = new JSONArray();
                int index = 0;
                for (boolean b : answers) {
                    if (b) answer.put(CHAR_TAG[index]);
                    index++;
                }
                o.put("answer", answer);
                array.put(o);
            }
            object.put("answers", array);
            Settings.setString(mView.getContext(), Settings.KEY_PREF_ANSWER, object.toString());
        } catch (Exception e) {
        }
    }

}
